//
//  DateExtension.swift
//  zhende
//
//  Created by 陆文宇 on 2017/6/9.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import Foundation

let yy_dfmatter: DateFormatter = DateFormatter() // 创建类对象，避免频繁创建DateFormatter对象(创建DateFormatter消耗性能大)

extension Date {
    
    func yy_formateString(formate: String) -> String {
        yy_dfmatter.dateFormat = formate
        return yy_dfmatter.string(from: self)
    }
    
    func yy_timeIntervalString(since date: Date = Date()) -> String {
        let components: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self, to: date)
        if components.year! > 0 {
            return yy_formateString(formate: "YYYY-MM-dd")
        }
        if components.month! > 0 {
            return yy_formateString(formate: "YYYY-MM-dd")
        }
        if components.day! > 0 {
            if components.day! > 10 {
                return yy_formateString(formate: "YYYY-MM-dd")
            }
            return "\(components.day!)天前"
        }
        if components.hour! > 0 {
            return "\(components.hour!)小时前"
        }
        if components.minute! > 0 {
            return "\(components.minute!)分钟前"
        }
        return "刚刚"
    }
    
}

extension String {
    
    func yy_timeStampToFormateString(formate: String) -> String! {
        if let timeSta = TimeInterval(self) {
            let date = Date(timeIntervalSince1970: timeSta)
            return date.yy_formateString(formate: formate)
        }
        return nil
    }
    
}

extension Int {
    
    func yy_timeStampToFormateString(formate: String) -> String! {
        let timeSta = TimeInterval(self)
        let date = Date(timeIntervalSince1970: timeSta)
        return date.yy_formateString(formate: formate)
    }
    
}
